package com.slz3.business.frame.util;

import lombok.Data;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author fengshiyou  on 2018/12/5 12:15 PM
 */
@Data
public class BeanValidators {

    /**
     * 默认消息值
     */
    private static final String DEFAULT_MSG = "不能为空";
    /**
     * 属性验证器
     */
    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * 参数返回结果
     */
    @Data
    public static class ValidatorResult {

        private List<FieldError> fieldErrors;
        private Boolean result = true;

        public Boolean hasError() {
            return !this.result;
        }

        public List<FieldError> getErrorList() {
            return this.fieldErrors;
        }

    }

    /**
     * 参数校验错误值
     */
    @Data
    public static class FieldError {
        private String field;
        private String value;
    }



    /**
     * 验证实例属性
     *
     * @param object
     * @return
     */
    public static ValidatorResult validate(Object object) {
        ValidatorResult validatorResult = new ValidatorResult();
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object);
        if (!constraintViolations.isEmpty()) {
            List<FieldError> errors = new ArrayList<>();
            constraintViolations.stream().forEach(item -> {
                FieldError fieldError = new FieldError();
                fieldError.setField(item.getPropertyPath().toString());
                fieldError.setValue(buildMessage(item.getMessage()));
                errors.add(fieldError);
                validatorResult.setFieldErrors(errors);
            });
            validatorResult.setResult(false);
        }
        return validatorResult;
    }

    private static String buildMessage(Object msg) {
        return msg == null ? DEFAULT_MSG : msg.toString();
    }

}
